package com.black.knight.chess.calls;

import org.restlet.resource.ClientResource;

import android.widget.EditText;

import com.black.knight.chess.R;
import com.black.knight.chess.RegistrationActivity;
import com.black.knight.chess.common.Base;
import com.black.knight.chess.common.UserResource;
import com.black.knight.chess.model.SettingsModel;

public class CheckUsernameCall implements Runnable {

	private String username;
	
	private RegistrationActivity context;
	
	private Base base = null;
	
	public CheckUsernameCall(String username, RegistrationActivity context) {
		this.context = context;
		this.username = username;
	}
	
	@Override
	public void run() {
		ClientResource cr = new ClientResource(SettingsModel.SERVICE_URL + "/users/" + username);
		
		cr.setRequestEntityBuffering(true);
		
		UserResource resource = cr.wrap(UserResource.class);
		
		try {
			base = resource.checkExistance();
		} catch (Exception e) {
			return;
		}
		
		if(base.getSuccess()) {
			context.runOnUiThread(new Runnable() {
				@Override
				public void run() {
					try {
						final EditText usernameInputField = (EditText) context.findViewById(R.id.usernameInputField);
						
						if(username.equals(usernameInputField.getText().toString())) {
							usernameInputField.setError(context.getResources().getString(R.string.username_already_exist));
						} else {
							usernameInputField.setError(null);
						}
					} catch (Exception e) { }
				}
			});
		}
	}
}
